package com.example.commonlib.httplib.utils;

import android.support.annotation.NonNull;

import com.google.gson.TypeAdapter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.Reader;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * Created by guitiancheng on 2018/6/27.
 * Introduction:
 */
public class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final TypeAdapter<T> adapter;

    public GsonResponseBodyConverter(TypeAdapter<T> adapter) {
        this.adapter = adapter;
    }

    @Override
    public T convert(@NonNull ResponseBody value) throws IOException {
        Reader reader = value.charStream();
        StringBuilder builder = new StringBuilder();
        char[] chars = new char[1024];
        int length;
        while ((length = reader.read(chars)) != -1) {
            builder.append(new String(chars, 0, length));
        }
        String responseData = builder.toString();
        try {
            JSONObject object = new JSONObject(responseData);
            String id = object.optString("code");
            if ("0".equals(id)) {
                return adapter.fromJson(object.toString());
            } else {
                object.remove("data");
                return adapter.fromJson(object.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
        } finally {
            value.close();
        }
        return null;
    }
}